﻿/**
 * Supports layout of a *single* map on the page:
 *    addition of the current user marker
 *    addition of other users' markers
 *    movement of current user's marker
 *    reverse geocoded caption (place name from coordinates)
 */

var map = undefined;
var txtLng = undefined;
var txtLat = undefined;
var txtName = undefined;

var MARKER_COLOR_COUNT = 8;
var marker_count = 0;

var latlng = undefined;
var myMarker = undefined;
var THIS_IS_YOU = "Это вы!";

function setMyPosition() {
    if (txtLat) txtLat.value = latlng.lat().toFixed(6);
    if (txtLng) txtLng.value = latlng.lng().toFixed(6);
    myMarker.info.close();
    myMarker.mk.setPosition(latlng);
    codeLatLng(latlng.lat(), latlng.lng());
    if (txtName) decodeLatLong();
}

function centerMe() {
    map.setCenter(latlng);
}

function initializeMap(params) {
    latlng = new google.maps.LatLng(params.latitude, params.longitude);
    var myOptions = { 
        zoom: 15,
        center: latlng, 
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true };
    map = new google.maps.Map($("#" + params.mapId)[0], myOptions);
    codeLatLng(latlng.lat(), latlng.lng());

    myMarker = addMarkerMyself({title: params.title,
        gender: params.gender, 
        latitude: params.latitude, 
        longitude: params.longitude});

    var latRes = $("#" + params.txtLatId);
    txtLat = latRes.length > 0 ? latRes[0]: undefined;
    var lngRes = $("#" + params.txtLngId);
    txtLng = lngRes.length > 0 ? lngRes[0] : undefined;
    var nameRes = $("#" + params.txtNameId);
    txtName = nameRes.length > 0 ? nameRes[0] : undefined;
    if (txtLat) txtLat.value = params.latitude;
    if (txtLng) txtLng.value = params.longitude;

    if (params.canMoveMyself == true) {
        google.maps.event.addListener(map, 'click', function(overlay, point) {
            latlng = overlay.latLng;
            setMyPosition();
        });
    }
}

function addMarker(params) {
    var marker = new google.maps.Marker({ 
        position: new google.maps.LatLng(params.latitude, params.longitude),
        title: params.title,
        icon: params.icon,
        zIndex: params.zIndex});
    marker.setMap(map);

    var infoWindow = new google.maps.InfoWindow(
        {content: params.html});

    google.maps.event.addListener(marker, 'click', function() {
        infoWindow.open(map, marker);
    });

    return {mk: marker, info: infoWindow};
}

function addMarkerMyself(params) {
    return addMarker({latitude: params.latitude,
        longitude: params.longitude, 
        title: THIS_IS_YOU,
        icon: "Images/map_marker_myself_" + params.gender + ".png",
        html: '<div id="user">' +
        '<img src="Images/this_attribute_' + params.gender + '.png" alt="' + THIS_IS_YOU + '"/>&nbsp;' +
        '<span class="UserName Gender' + params.gender + '">' + params.title + '</span>' +
        '<br/>' + THIS_IS_YOU + '</div>',
        zIndex: 0xFFFFFFFF});
}

function addMarkerUser(params) {
    var marker = addMarker({latitude: params.latitude, 
        longitude: params.longitude, 
        title: params.title,
        icon: "Images/map_marker_" + marker_count + ".png", 
        html: '<div id="user">' +
        '<img src="Photo.aspx?id=' + params.id + '" alt="' + params.title + '" class="ImageBlock"/>' +
        '<span class="UserNameBlock"><span class="UserName Gender' + params.gender + '">' + 
        params.title + '</span></span></div>', 
        zIndex: undefined});

    marker_count = (marker_count + 1) % MARKER_COLOR_COUNT;

    return marker;
}

function updateLatLong(newLat, newLng) {
    if (newLat == latlng.lat() && newLng == latlng.lng()) return;

    if (newLat == NaN) newLat = latlng.lat();
    if (newLat > 90.0) newLat = 90.0;
    if (newLat < -90.0) newLat = -90.0;

    if (newLng == NaN) newLng = latlng.lng();
    if (newLng > 179.0) newLng = 179.0;
    if (newLng < -180.0) newLng = -180.0;

    latlng = new google.maps.LatLng(newLat, newLng);
    setMyPosition();
    centerMe();
}

function codeLatLng(lat, lng) {
    if ($("#reverseGeocoded").length == 0) return;

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'latLng': latlng },
                function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results[0]) {
                            $("#reverseGeocoded").html(results[0].formatted_address);
                        } else {
                            $("#reverseGeocoded").html("&lt;название местоположения определить не удается&gt;");
                        }
                    }
                });
}

function decodeLatLong() {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'latLng': latlng },
                function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results[0]) {
                            result = results[0].formatted_address;
                        } else {
                            result = "";
                        }
                        txtName.value = result;
                    }
                });
}

function decodeName(name) {
    if (name.length == 0) return;

    geocoder = new google.maps.Geocoder();
    geocoder.geocode({ address: name },
        function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    latlng = results[0].geometry.location;
                    setMyPosition();
                    centerMe();
                }
            }
        });
}